package com.gsafety.wellsfort.service.course;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gsafety.wellsfort.common.context.LoginContextUtil;
import com.gsafety.wellsfort.common.enums.RoleGroupEnum;
import com.gsafety.wellsfort.common.util.ApiResponse;
import com.gsafety.wellsfort.common.util.DateUtil;
import com.gsafety.wellsfort.common.util.ResultCode;
import com.gsafety.wellsfort.dao.course.*;
import com.gsafety.wellsfort.dao.knowledge.*;
import com.gsafety.wellsfort.dao.organization.ClassDAO;
import com.gsafety.wellsfort.dao.organization.StudentDAO;
import com.gsafety.wellsfort.dao.security.AdminDAO;
import com.gsafety.wellsfort.dao.security.RoleDAO;
import com.gsafety.wellsfort.domain.dto.course.WorkFinishPreviewDTO;
import com.gsafety.wellsfort.domain.dto.course.WorkPublishDTO;
import com.gsafety.wellsfort.domain.dto.course.WorkPublishQueryDTO;
import com.gsafety.wellsfort.domain.dto.ids.WorkPublishIdDTO;
import com.gsafety.wellsfort.domain.model.course.*;
import com.gsafety.wellsfort.domain.model.knowledge.Work;
import com.gsafety.wellsfort.domain.model.organization.Class;
import com.gsafety.wellsfort.domain.model.organization.Student;
import com.gsafety.wellsfort.domain.model.security.Admin;
import com.gsafety.wellsfort.domain.model.security.Role;
import com.gsafety.wellsfort.domain.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class WorkPublishService {
    @Autowired(required = false)
    CourseDAO courseDAO;

    @Autowired(required = false)
    LessonPeriodDAO lessonPeriodDAO;

    @Autowired(required = false)
    CourseRangeDAO courseRangeDAO;

    @Autowired(required = false)
    CoursewareDAO coursewareDAO;

    @Autowired(required = false)
    TeachingMaterialDAO materialDAO;

    @Autowired(required = false)
    TeachingAidDAO teachingAidDAO;

    @Autowired(required = false)
    WorkDAO workDAO;

    @Autowired(required = false)
    AdminDAO adminDAO;

    @Autowired(required = false)
    ExamPaperDAO examkDAO;

    @Autowired(required = false)
    StudentWorkDAO studentWorkDAO;

    @Autowired(required = false)
    WorkPublishDAO workPublishDAO;

    @Autowired(required = false)
    WorkPublishRangeDAO workPublishRangeDAO;

    @Autowired(required = false)
    LearningProgressDAO learningProgressDAO;


    @Autowired(required = false)
    StudentDAO studentDAO;
    @Autowired(required = false)
    ClassDAO classDAO;

    @Autowired(required = false)
    private RoleDAO roleDAO;

    @Autowired(required = false)
    private WorkQuestionDAO workQuestionDAO;

    public ApiResponse<WorkPublishDTO> publishStuWork(WorkPublishDTO workPublishDTO){
        ApiResponse<WorkPublishDTO> apiResponse=null;
        try{
            WorkPublish wkPublish=new WorkPublish();
            BeanUtils.copyProperties(workPublishDTO,wkPublish);
            if(workPublishDTO.getPublishTime()!=null){
                wkPublish.setPublishTime(DateUtil.parseTime(workPublishDTO.getPublishTime()));
            }
            if(LoginContextUtil.getAdmin()!=null){
                //状态设置为已发布
                wkPublish.setPublishState((byte)1);
                wkPublish.setPublishUserId(LoginContextUtil.getAdmin().getId());
            }else{
                return ApiResponse.error(ResultCode.ERROR.getCode(),"管理员未登录!");
            }
            if(workPublishDTO.getWorkId()!=null){
                Map<String,Object> questionParam=new HashedMap();
                questionParam.put("workId",workPublishDTO.getWorkId());
                List<QuestionVO> questionList=workQuestionDAO.selectByParam(questionParam);
                if (questionList.size()<=0){
                    return ApiResponse.error(ResultCode.ERROR.getCode(),"该作业没有题目，不能发布!");
                }
            }
            //作业发布编辑
            if(workPublishDTO.getId()!=null){
                //清除课程范围
                workPublishRangeDAO.deleteByWorkPublishId(workPublishDTO.getId());
                //清除学生作业
                studentWorkDAO.deleteByWorkPublishId(workPublishDTO.getId());
                //更新发布记录
                WorkPublish workPublishDB=workPublishDAO.selectByPrimaryKey(workPublishDTO.getId());
                workPublishDB.setWorkId(workPublishDTO.getWorkId());
                if(workPublishDTO.getPublishTime()!=null){
                    Date publicDate=DateUtil.parseTime(workPublishDTO.getPublishTime());
                    workPublishDB.setPublishTime(publicDate);
                }
                workPublishDAO.updateByPrimaryKeySelective(workPublishDB);

            }else{
                wkPublish.setPublishNums(1);
                wkPublish.setFinishNums(0);
                workPublishDAO.insertSelective(wkPublish);
                workPublishDTO.setId(wkPublish.getId());
            }
            //更新作业发布次数
            Work wkDB=workDAO.selectByPrimaryKey(workPublishDTO.getWorkId());
            if(wkDB!=null)
            {
                if(wkDB.getPublicTimes()==null){
                    wkDB.setPublicTimes(0);
                }
                wkDB.setPublicTimes(wkDB.getPublicTimes()+1);
                workDAO.updateByPrimaryKeySelective(wkDB);
            }
            //课程范围,如果是平台用户
            Integer[] classIds;
            if(workPublishDTO.getIsPlatform()!=null&&workPublishDTO.getIsPlatform()==1){
                classIds=(Integer[]) classDAO.selectAll().toArray();
            }else{
                classIds=workPublishDTO.getClassIds();
            }
            if(classIds!=null){
                StudentWork stuWork=null;
                Class cls= null;
                for(Integer clsId:classIds){
                    cls=classDAO.selectByPrimaryKey(clsId);
                    WorkPublishRange record=WorkPublishRange.builder().workPublishId(workPublishDTO.getId())
                            .classId(clsId)
                            .schoolId(cls.getSchoolId())
                            .creator(LoginContextUtil.getAdmin().getId())
                            .createTime(new Date()).build();
                    workPublishRangeDAO.insert(record);
                    //根据班级Id下的学生,生成作业
                    Map<String,Object>stuParam=new HashedMap();
                    stuParam.put("classId",clsId);
                    List<Student> stuList=studentDAO.listQuery(stuParam);
                    for(Student stu:stuList){
                        stuWork =new StudentWork();
                        stuWork.setClassId(clsId);
                        stuWork.setStudentId(stu.getId());
                        stuWork.setCourseId(wkPublish.getCourseId());
                        stuWork.setFinishState((byte)0);
                        stuWork.setPublishTime(wkPublish.getPublishTime());
                        stuWork.setLessonPeriodId(wkPublish.getLessonPeriodId());
                        stuWork.setWorkId(wkPublish.getWorkId());
                        stuWork.setWorkPublishId(wkPublish.getId());
                        stuWork.setIsPassed((byte)0);
                        studentWorkDAO.insert(stuWork);
                    }
                }
            }

            apiResponse=ApiResponse.success(workPublishDTO);
        }catch (Exception e){
            apiResponse=ApiResponse.error(ResultCode.PUBLISH_WORK_ERROR,e.getMessage());
            e.printStackTrace();
        }


        return apiResponse;
    }
    public ApiResponse<WorkPublishIdDTO> cancelWorkPublish(WorkPublishIdDTO workPublishEditDTO){
        ApiResponse<WorkPublishIdDTO> apiResponse=null;
        try{
            WorkPublish workPublishDB= workPublishDAO.selectByPrimaryKey(workPublishEditDTO.getId());
            if(workPublishDB!=null){
                workPublishDB.setPublishState((byte)0);
                workPublishDAO.updateByPrimaryKeySelective(workPublishDB);
            }
/*            if(workPublishEditDTO.getId()!=null){
                //清除课程范围
                workPublishRangeDAO.deleteByWorkPublishId(workPublishEditDTO.getId());
                //清除学生作业
                studentWorkDAO.deleteByWorkPublishId(workPublishEditDTO.getId());
                //更新发布次数
                WorkPublish workPublishDB= workPublishDAO.selectByPrimaryKey(workPublishEditDTO.getId());
                workPublishDB.setPublishNums(workPublishDB.getPublishNums()+1);
                workPublishDAO.updateByPrimaryKeySelective(workPublishDB);
            }*/
            apiResponse=ApiResponse.success();
        }catch (Exception e){
            apiResponse=ApiResponse.error(ResultCode.PUBLISH_WORK_ERROR,e.getMessage());
            e.printStackTrace();
        }
        return apiResponse;
    }
    public ApiResponse<WorkPublishIdDTO> againWorkPublish(WorkPublishIdDTO workPublishEditDTO){
        ApiResponse<WorkPublishIdDTO> apiResponse=null;
        try{
            WorkPublish workPublishDB= workPublishDAO.selectByPrimaryKey(workPublishEditDTO.getId());
            if(workPublishDB!=null){
                workPublishDB.setPublishState((byte)1);
                workPublishDAO.updateByPrimaryKeySelective(workPublishDB);
            }
/*            if(workPublishEditDTO.getId()!=null){
                //清除课程范围
                workPublishRangeDAO.deleteByWorkPublishId(workPublishEditDTO.getId());
                //清除学生作业
                studentWorkDAO.deleteByWorkPublishId(workPublishEditDTO.getId());
                //更新发布次数
                WorkPublish workPublishDB= workPublishDAO.selectByPrimaryKey(workPublishEditDTO.getId());
                workPublishDB.setPublishNums(workPublishDB.getPublishNums()+1);
                workPublishDAO.updateByPrimaryKeySelective(workPublishDB);
            }*/
            apiResponse=ApiResponse.success();
        }catch (Exception e){
            apiResponse=ApiResponse.error(ResultCode.PUBLISH_WORK_ERROR,e.getMessage());
            e.printStackTrace();
        }
        return apiResponse;
    }
    public ApiResponse<WorkPublishEditVO> getPublicWorkDetail(WorkPublishIdDTO workPublishIdDTO){
        Integer id=workPublishIdDTO.getId();
        ApiResponse<WorkPublishEditVO> apiResponse=null;
        try{
            WorkPublish workPublish= workPublishDAO.selectByPrimaryKey(id);
            String workName="";
            if(workPublish.getWorkId()!=null){
                Work w=workDAO.selectByPrimaryKey(workPublish.getWorkId());
                workName=w.getWorkTitle();
            }
            WorkPublishEditVO workPublishEditVO=WorkPublishEditVO.builder().workName(workName).build();
            BeanUtils.copyProperties(workPublish,workPublishEditVO);
            apiResponse=ApiResponse.success(workPublishEditVO);
        }catch (Exception e){
            apiResponse=ApiResponse.error();
            e.printStackTrace();
        }
        return apiResponse;
    }
    public ApiResponse<List<WorkPublishVO>> listPublishWork(WorkPublishQueryDTO dtoParams) {
        ApiResponse<List<WorkPublishVO>> apiResponse=null;
        if (LoginContextUtil.getAdmin() != null) {
            //添加数据权限判断
            Admin admin = LoginContextUtil.getAdmin();
            if (admin == null) {
                return ApiResponse.error(ResultCode.INVALID_PARAM);
            }
            List<Integer> ids = new ArrayList<>();
            List<Admin> adminList = new ArrayList<>();
            List<Role> list = roleDAO.selectRoleByAdminId(admin.getId());
            if (list != null && list.size() > 0) {
                if (RoleGroupEnum.SCHOOL_ADMIN.getCode().equals(list.get(0).getRoleGroup().intValue())) {
                    //学校管理员,查看学校创建
                    adminList = adminDAO.selectBySchoolId(admin.getSchoolId());
                } else if (RoleGroupEnum.TEACHER_ADMIN.getCode().equals(list.get(0).getRoleGroup().intValue())) {
                    //教师平台，查看自己创建
                    adminList.add(admin);
                }
                for (Admin ad : adminList) {
                    ids.add(ad.getId());
                }
            }
            dtoParams.setIds(ids);
        }
        Page page= PageHelper.startPage(dtoParams.getPageNo(), dtoParams.getPageSize());
        List<WorkPublishVO> voList= workPublishDAO.selectByParam(dtoParams);
        Admin admin;
        Course course;
        LessonPeriod lessonPeriod;
        for(WorkPublishVO vo:voList){
            if(vo.getPublishUserId()!=null){
                admin=adminDAO.selectByPrimaryKey(vo.getPublishUserId());
                if(admin!=null){
                    vo.setPublishUserName(admin.getName());
                }

            }
            if(vo.getPublishNums()!=null){
                Integer publishNum=studentWorkDAO.countPublishNum(vo.getId());
                vo.setPublishNums(publishNum);
                WorkPublish wp=workPublishDAO.selectByPrimaryKey(vo.getId());
                wp.setPublishNums(publishNum);
                workPublishDAO.updateByPrimaryKeySelective(wp);
            }
            vo.setFinishNums(studentWorkDAO.countPublishFinishNum(vo.getPublishUserId(),null,1));
            if(vo.getCourseId()!=null){
                course=courseDAO.selectByPrimaryKey(vo.getCourseId());
                if(course!=null){
                    vo.setCourseName(course.getName());
                }
            }
            if(vo.getLessonPeriodId()!=null){
                lessonPeriod=lessonPeriodDAO.selectByPrimaryKey(vo.getLessonPeriodId());
                if(lessonPeriod!=null){
                    vo.setLessonPeriodName(lessonPeriod.getName());
                }
            }
        }
        PageInfo pageInfo= new PageInfo(page);
        pageInfo.setList(voList);
        apiResponse=ApiResponse.success(voList,(int)pageInfo.getTotal());
        return apiResponse;
    }

    public ApiResponse<WorkFinishPreviewVO> finishPreview(WorkFinishPreviewDTO workFinishPreviewDTO){
        ApiResponse<WorkFinishPreviewVO> apiResponse=null;
        try{
            WorkFinishPreviewVO workFinishPreviewVO= WorkFinishPreviewVO.builder().build();
            Page page= PageHelper.startPage(workFinishPreviewDTO.getPageNo(), workFinishPreviewDTO.getPageSize());
            List<StudentWorkFinishRecordVO> studentWorkFinishRecordVOList =studentWorkDAO.selectByFinishPreviewDTO(workFinishPreviewDTO);
            List<Map<String,Object>> classNameList=new ArrayList<Map<String,Object>>();
            Class cls;
            Student stu;
            Set<Integer> clsSet=new HashSet<Integer>();
            //处理学生信息
            for(StudentWorkFinishRecordVO recordVO : studentWorkFinishRecordVOList){
                if(recordVO.getClassId()!=null){
                    clsSet.add(recordVO.getClassId());
                    cls=classDAO.selectByPrimaryKey(recordVO.getClassId());
                    if(cls!=null)recordVO.setClassName(cls.getName());
                }
                if(recordVO.getStudentId()!=null){
                    stu=studentDAO.selectByPrimaryKey(recordVO.getStudentId());
                    if(stu!=null)recordVO.setStudentName(stu.getName());
                }
                if(recordVO.getIsPassed()==null||recordVO.getIsPassed()==0){
                    recordVO.setIsPassedText("不通过");
                }else if(recordVO.getIsPassed()==1){
                    recordVO.setIsPassedText("通过");
                }
            }
            //处理班级
            for(Integer clsId:clsSet){
                Map<String,Object> classNameMap=new HashMap<String,Object>();
                cls=classDAO.selectByPrimaryKey(clsId);
                classNameMap.put("classId",clsId);
                if(cls!=null)classNameMap.put("className",cls.getName());
                classNameList.add(classNameMap);
            }
            workFinishPreviewVO.setClassNameList(classNameList);
            //处理作业相关信息
            if(studentWorkFinishRecordVOList.size()>0){
                StudentWorkFinishRecordVO recordVO= studentWorkFinishRecordVOList.get(0);
                if(recordVO.getWorkTitle()!=null)workFinishPreviewVO.setWorkTitle(recordVO.getWorkTitle());
                if(recordVO.getWorkId()!=null){
                    workFinishPreviewVO.setWorkId(recordVO.getWorkId());
                }
                if(recordVO.getCourseId()!=null){
                    Course course=courseDAO.selectByPrimaryKey(recordVO.getCourseId());
                    if(course!=null)workFinishPreviewVO.setCourseName(course.getName());
                }
                if(recordVO.getLessionPeriodId()!=null){
                    LessonPeriod lessonPeriod=lessonPeriodDAO.selectByPrimaryKey(recordVO.getLessionPeriodId());
                    if(lessonPeriod!=null)workFinishPreviewVO.setCourseName(lessonPeriod.getName());
                }
            }
            workFinishPreviewVO.setStudentWorkFinishRecordVOList(studentWorkFinishRecordVOList);
            PageInfo pageInfo= new PageInfo(page);
            pageInfo.setList(studentWorkFinishRecordVOList);
            apiResponse=ApiResponse.success(workFinishPreviewVO,(int) pageInfo.getTotal());
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            apiResponse=ApiResponse.error(ResultCode.ERROR,e.getMessage());
        }

        return apiResponse;
    }
}
